package api

import (
	"strconv"
	"team-evaluate/global"
	"team-evaluate/internal/model"
	"team-evaluate/internal/service"
	"team-evaluate/pkg/app"
	"team-evaluate/pkg/errcode"
	"team-evaluate/pkg/util"

	"github.com/gin-gonic/gin"
)

// @Summary 用户登录
// @Produce  json
// @Tags 登录
// @Param account body string true "用户邮箱" maxlength(20)
// @Param password body string true "密码"
// @Success 200 {object} app.HttpSuccessResult "成功"
// @Failure 400 {object} errcode.Error "请求错误"
// @Failure 500 {object} errcode.Error "内部错误"
// @Router /login [post]
func Login(c *gin.Context) {
	param := model.LoginRequest{}
	response := app.NewResponse(c)
	valid, errs := app.BindAndValid(c, &param)
	if !valid {
		global.Logger.Errorf("app.BindAndValid errs: %v", errs)
		response.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
		return
	}
	p, err := util.StrutToString(param)
	if err == nil {
		c.Set("request_params", p)
	}
	svc := service.New(c.Request.Context())
	userInfo, err := svc.CheckAuth(&param)
	if err != nil {
		global.Logger.Errorf("svc.CheckAuth err: %v", err)
		response.ToErrorResponse(errcode.LoginCheckAuthFail)
		return
	}
	userIdStr := strconv.Itoa(int(userInfo.ID))
	token, err := app.GenerateToken(userIdStr)

	if err != nil {
		global.Logger.Errorf("app.GenerateToken err: %v", err)
		response.ToErrorResponse(errcode.UnauthorizedTokenGenerate)
		return
	}

	// 这里将userIdStr和token存入redis，这样可以限制账号同一时间只能登录一台设备
	err = global.RDb.Set("token:"+userIdStr, token, global.JWTSetting.Expire).Err()
	if err != nil {
		global.Logger.Errorf("rdb.Set err: %v", err)
		response.ToErrorResponse(errcode.LoginFail)
		return
	}

	response.ToResponseObj(gin.H{
		"token":     token,
		"user_id":   userInfo.ID,
		"user_name": userInfo.Name,
	})
}
